<template>
  <div class="alteration-wrapper">
    <a-spin :spinning="spinning">
      <div class="contentBox">
        <tabs :defaultTagId="defaultTagId" :custom="false" :tabPaneData="tabPaneData" @change="callback"></tabs>
        <div class="content">
          <div id="baseInfo" class="baseInfo">
            <div class="title">
              基本信息
            </div>
            <div class='form-box'>
              <a-form :form="form" @submit="handleSubmit">
                <div class="row-item" v-for="(rowItem, rowIndex) in baseInfoArr" :key="rowIndex">
                  <div v-for="(item, index) in rowItem.items" :key="index" style="width: 100%;" class="cell-item" :class="rowItem.items.length === 1 ? '' : 'interal'">
                    <a-form-item :label="item.label">
                      <!-- && item.id!='planActivityReference' -->
                      <a-input autocomplete="off" v-if="item.formType === 'text'" style="width: 100%;" :placeholder="item.id=='requestNumber' ? '自动生成' : '请输入'" :allowClear="true"
                        v-decorator="[ item.id, { initialValue: item.value, rules: [{ required: item.id=='requestNumber' ? false : item.required, message: `请选择${item.label}！` }] }]"
                        :disabled="item.id=='requestNumber'?true:false"></a-input>
                      <a-button v-else-if="item.formType === 'button' && item.id=='responsibleUserReference'" @click="btnClick(item.id)" style="color:rgba(0, 0, 0, 0.65);">
                        <span v-if="responsibleUserReference.name || item.value" style="color:rgba(0, 0, 0, 0.65);">{{ responsibleUserReference.name || item.value }}</span>
                        <span v-else style="color:rgba(0, 0, 0, 0.25);">请选择</span>
                      </a-button>
                      <!-- <a-input v-else-if="item.formType === 'text' && item.id=='planActivityReference'" style="width: 100%;" placeholder="请选择" :allowClear="true"
                        v-decorator="[ item.id, { initialValue: item.value, rules: [{ required: item.required, message: `请选择${item.label}！` }] }]"
                        @click="btnClick(item.id)">
                      </a-input> -->
                      <a-input v-if="item.formType === 'textarea'" autocomplete="off" type="textarea"  style="width: 100%;" :allowClear="true" :rows="4" :maxLength="500"
                            v-decorator="[ item.id, { initialValue: item.value, rules: [{ required: item.id=='requestNumber' ? false : item.required, message: `请选择${item.label}！` }] }]"></a-input>
                      <!-- <template v-if="item.formType === 'textarea'">
                        <div class="properContent">
                          <a-input autocomplete="off" type="textarea"  style="width: 100%;" :allowClear="true" :rows="4" :maxLength="500"
                            v-decorator="[ item.id, { initialValue: item.value, rules: [{ required: item.id=='requestNumber' ? false : item.required, message: `请选择${item.label}！` }] }]"></a-input>
                            <div class="contentLength"><span>{{!item.value ? 0: item.value.length}}</span>/500</div>
                        </div>
                      </template> -->
                      <a-select
                        v-else-if="item.formType === 'select'"
                        style="width: 100%"
                        v-decorator="[ item.id, { initialValue: item.value, rules: [{ required: item.required, message: `请选择${item.label}！` }] }]"
                        placeholder="请选择"
                        @change="changeSelect($event,item.label)"
                        :allowClear="true">
                          <a-select-option v-for="selectItem in item.selects" :key="selectItem.id" :value="selectItem.id">{{selectItem.name}}</a-select-option>
                      </a-select>
                      <a-date-picker v-else-if="item.formType === 'Date'" style="width: 100%" :locale="locale" valueFormat="YYYY-MM-DD" v-decorator="[ item.id, { initialValue: item.value, rules: [{ required: item.required, message: `请选择${item.label}！` }] }]" :allowClear="true"></a-date-picker>
                    </a-form-item>
                  </div>
                </div>
              </a-form>
              <!-- <div class="row-item">
                <a-form-item label="相关附件">
                  <upload-attachment :defaultFileList="fileArrList" @upload="upload" @remove="handleRemove" @download="routerPage"></upload-attachment>
                </a-form-item>
              </div> -->
            </div>
          </div>
          <div id="associatedTaskBook" class="associatedTaskBook">
            <div class="titleBox">
              <span class="title">关联的项目任务书</span>
            </div>
            <div class="tableContent">
              <a-empty description="暂无数据" class="nodata"/>
              <!-- <attachment :bookOid="bookOid" :bookVersion="bookVersion" typeFrom="1" @onlyOne="onlyOneHandle" @selectedData="selectedData"></attachment> -->
            </div>
          </div>
          <div id="processSet" class="processSet"> 
            <div class="title">流程设置</div>
            <div class="process-explain explain">
              流程说明： <br>
              一、不可控因素“十二条”：<br>
              1、 客户或市场需求变化；<br>
              2、 大生产期间优先保供（需所在单位第一负责人确认）；<br>
              3、 客户试用验证受阻（集团外部客户：需营销公司总经理确认；集团内部客户：需求提出方的研究院院长确认）；<br>
              4、集团内配套零部件项目或主机项目延期造成对方影响（零部件与主机开发必须分属不同研究院，由对方研究院长确认）；<br>
              5、 国家/行业/地方政策、标准、法律法规变化；<br>
              6、 国家检测机构因素；<br>
              7、 自然灾害；<br>
              8、 天气变化；<br>
              9、 意外事故；<br>
              10、长周期外购件供应商未按合同要求供货（需商务或质保部第一负责人确认）；<br>
              11、出口发运周期变化（需发运部门第一负责人确认）；<br>
              12、其余研发管理总部确认的不可控因素。<br>
              二、实施要求：<br>
              1、因不可控因素“十二条”造成研发项目（或节点）延期超过1个月或总开发周期的1/5时，方可调整项目（或节点）完成时间。除此之外，不允许调整项目（或节点）完成时间；<br>
              2、所有项目延期申请需按要求附上相应的证明材料（如各相关部门负责人对延期原因确认的签字文件等），或在事业部审批节点中增加对应部门负责人审批节点。<br>
              <br>
            </div>
            <!-- 编辑的时候不展示流程设置 选人-->
            <div class="process-user-select" v-if="creator">
              <processUser ref="processUser" :formData='processUsers'></processUser>
            </div>
            <div class="process-user-select" v-if="sourceData.operation=='修改'">
              <commonProcessSettings ref="commonProcessSettings" :formData="processUsers" :Oid='sourceData.pboOid'  @fields='fields'></commonProcessSettings>
            </div>
            <!--    操作按钮的弹框集合-->
          <commonProcess v-if="sourceData.operation=='修改'" ref="peocessCon" :step-arr="stepArr" :process-table-is-show="true"
                         :bottom-describe-is-show="true" :table-arr="tableArr"
                         :radio-arr="radioArr" @submitProcessPeople="submitProcessPeople"></commonProcess>
          </div>
        </div>
        <div class="footer" v-if="sourceData.operation!='修改'">
            <a-button @click="backData">返回</a-button>
            <a-button type="primary" @click="submitData">提交</a-button>
        </div>
      </div>
    </a-spin>
    <common-modal
        modalTitle="选择负责人"
        :modalVisible="addMemberAddDialog"
        @handleOk="selectedMember"
        @handCancel="addMemberAddDialog=false"
        :selectType="'radio'"
        :itemArr="projectMemberSelectData"
      ></common-modal>
      <!-- 选择所属阶段/计划活动的弹框 -->
      <!-- <common-modal-activity
        :modalVisible="modalVisibleActive"
        isActivity="所属阶段"
        @handleOkActivity="handleOkActivity"
        @handCancel="handCancel"
        selectType="radio"
      ></common-modal-activity> -->
    <!-- <project-member-add-dialog v-if="addMemberAddDialog" ref="addMemberAddDialog" :dialogVisible="addMemberAddDialog" :roleData="projectMemberSelectData" @cancel="addMemberAddDialog=false" @ok="selectedMember"></project-member-add-dialog> -->
  </div>
</template>
  
<script>
import tabs from "@/components/tabs/tabs"
import commonModal from "@/components/common/commonModal.vue";
// import uploadAttachment from "../../projectRisk/createRisk/onUpload/uploadAttachment";
// import attachment from '../../projectTaskBook/mainTaskBook/attachment'
import processUser from './modules/processUser'
import { getCreateProject } from '@/api/singleProject'
import { getTaskBookByProject, TaskBookAttachmentInfo, downloadAttachmentFile } from '@/api/taskBook';
import { getPageSelectPrincipal, getProcessSteps, completeWorkItem, reassignWorkItem, getRouting, getDisposeStatus, getWFSelectPrincipal,updateTeamPrincipal } from "@/api/fileSingle.js"
import {getManagerMiddle, searchUserIdMiddle} from "@api/singleProject";
import { saveFile } from '@/utils/util'
import commonProcessSettings from '@/components/common/commonProcessSettings.vue'//流程处理选择人员（修改）
import commonProcess from '@/components/processCommon/approveProcess'
import { saveChangeRequest, getProjectTaskBook } from '@/api/projectAlteration'
import { editProject } from "@api/singleProject"
import commonTable from '@/components/common/commonTable'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
// import commonModalActivity from "../../projectQuestion/addQuestion/commonModal/commonModal";
import {chooseUserList,baseInfoLay} from "../dataBase"
let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
export default {
  components: { tabs, processUser, commonTable, commonProcess, commonProcessSettings, commonModal },
  props: {
    creator: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
        locale,
        changeOid: '', // 变更oid
        spinning: false,
        defaultTagId: 'baseInfo',
        tabPaneData: [
          {
            tagId: 'baseInfo',
            tagName: '基本信息',
          
          },
          {
            tagId: 'associatedTaskBook',
            tagName: '关联的项目任务书',
          },
          {
            tagId: 'processSet',
            tagName: '流程设置',
          },
        ],
        baseInfoArr: [], // 基本信息布局
        formFidlds: {}, // 表格字段及value
        bookOid: '', // 任务书oid
        bookVersion:'',
        attachmentSelect: [], // 关联任务书表格选中
        processUsers: [],
        addMemberAddDialog: false, // 添加负责人
        responsibleUserReference: '',
        projectMemberSelectData: [],
        tableColumns: [
          {
            displayName: '文件名',
            name: 'name',
            key: 'name',
            scopedSlots: {
              customRender: "name"
            }
          },
          {
            displayName: '上次修改时间',
            name: 'updateTime',
            key: 'updateTime',
            fieldType: 'Date',
            dataType: 'String',
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender"
            }
          },
          {
            displayName: '创建者',
            name: 'updater',
            key: 'updater'
          }
        ],
        loadTable: false,
        choosedFile:[],//选中要移除的文件
        responsibleUserReferenceCopy:'',//负责人valueInner
        sourceData:[],//从待办过来的数据
        stepArr: [],//流程视图数据
        tableArr: [],//流程记录表格数据
        radioArr:[],
        radioVal1: '',//操作的选择
        desVal1: '',//操作意见
        reassignUser: '',//转办人
        modalVisibleActive:false,//所属阶段弹框
        fileArrList:[],// 上传附件
        planActivityReferenceId:'',//所属阶段id
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  mounted() {
    this.baseInfoHandle(baseInfoLay);//基本信息
    this._getPageSelectPrincipal() // 流程处理
    // this.sourceData = sessionStorage.getItem('changeAlterationData') ? JSON.parse(sessionStorage.getItem('changeAlterationData')) : {}
    // this.$store.commit('SET_CHANGEDATA',{name:'user'})
    // this.oid = sessionStorage.getItem('oid');
    // this.userId = userInfo.loginName
    // if(this.creator){
    //   this.changeOid = ''
    // }else{
    //   this.changeOid = sessionStorage.getItem('changeOid') || ''
    //   if(this.changeOid){
    //     this._TaskBookAttachmentInfo();
    //   }
    // }
    // if(this.sourceData && this.sourceData.operation == '修改'){
    //   this.getProcess();
    //   this.changeOid = this.sourceData['pboOid']
    //   this._TaskBookAttachmentInfo();
    //   this._getProcessSteps()
    //   this._getDisposeStatus()
    //   this.getRoutingIndex();
    // }else{
    //   this._getPageSelectPrincipal() // 流程处理
    // }
    // this._getProjectFourthNodes() // 所属交付阶段
    // this._getTaskBookByProject()
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          // console.log('Received values of form: ', values);
        }
      });
    },
    btnClick(val) {
      if (val === 'responsibleUserReference') {
        this.getManager();
      }else if(val === 'planActivityReference'){
        this.modalVisibleActive = true
      }
    },
    // 添加所属阶段
    handleOkActivity(val, name) {
      this.planActivityReferenceId = val[0];
      const { setFieldsValue } = this.form;
      setFieldsValue({
        planActivityReference:name
      })
      this.modalVisibleActive = false;
    },
    handCancel() {
      this.modalVisibleActive = false
    },
    selectedMember(selectedData) {
      this.addMemberAddDialog=false
      if (selectedData) {
        this.responsibleUserReferenceCopy = selectedData.userId
        this.responsibleUserReference = selectedData
      }
    },
    //获取任务书
    _getProjectTaskBook(){
      getProjectTaskBook({oid: this.changeOid, userId: this.userId}).then(({data})=>{
        if (data.success && data.data && data.data.length) {
            this.bookOid = data.data[0].bookOid
        } else {
          this.$message.error(data.message)
        }
      })
    },
    //查看附件
    _TaskBookAttachmentInfo() {
      TaskBookAttachmentInfo({ oid: this.changeOid, userId: this.userId }).then(({data}) => {
        if (data.success) {
          if (data.data && data.data.length) {
            let arrayList =  _.orderBy(data.data, ['updateTime'], ['desc'])//按照创建时间降序排序
            let fileArrList = []
            arrayList.forEach(item => {
              fileArrList.push({ uid: item.oid, name: item.name, status: 'done' })
            })
            this.fileArrList = fileArrList
            if (this.fileArrList.length === 1) {
              this.$emit('onlyOne', this.tableData)
            }
          } else {
            this.fileArrList = []
          }
        }else{
          this.fileArrList = []
          this.$message.error(data.message)
        }
      })
    },
    //预览附件
    routerPage(rows) {
      let names = rows.name;
      let str = names.substring(names.lastIndexOf(".")+1);
      let paramInfo = { userId: this.userId, oid: rows.oid }
      downloadAttachmentFile(paramInfo).then(results => {
        if (results && results.status === 200) {
          const blob = new Blob([results.data], {type: `application/${str}`})
          saveFile(blob, names)
        } else {
          this.$message.warn('导出异常')
        }
      })
    },
    _getProcessSteps() {
      getProcessSteps({oid: this.changeOid}).then((results) => {
        if (results && results.status === 200) {
          if (results.data.success) {
            if (results.data && results.data.data && results.data.data !== '' && results.data.data.length > 0) {
              this.stepArr = results.data.data.map((item) => {
                item.state = item.state.toLowerCase(); // 统一转化成小写
                return item;
              });
              let arr = results.data.data.filter((e)=>{
                return e.userFullName !=='';
              })
              this.stepArr = arr
              // }
            } else {
              this.stepArr = []
            }
          } else {
            this.stepArr = []
            this.$message.error(results.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    _getDisposeStatus() {
      // 获取交付物流程记录
      getDisposeStatus({oid: this.changeOid}).then((results) => {
      //  console.log(results)
        if (results && results.status === 200) {
          if (results.data && results.data.success == 'true') {
            if (results.data.data.length > 0) {
              this.tableArr = _.orderBy(results.data.data, ['workCompletedDate'], ['desc'])//按照创建时间降序排序
              this.tableArr.splice(0, 0, this.tableArr[this.tableArr.length - 1])      //把最后一个元素复制到首个
              this.tableArr.splice(-1, 1);       //删除最后一个元素
            } else {
              this.tableArr = []
            }
          } else {
            this.tableArr = []
            this.$message.error(results.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    // getRoutingIndex 获取流程操作
    getRoutingIndex() {
      getRouting({oid: this.sourceData.workItemOid}).then((results) => {
        if (results && results.status === 200) {
          if (results.data && results.data.success) {
            if (results.data.data && results.data.data.length > 0) {
              this.radioArr = results.data.data
            } else {
              this.radioArr = []
            }
          } else {
            this.radioArr = []
            this.$message.error(results.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    _getProjectFourthNodes() {
      if(this.changeOid) {
        this._editProject()
      } else {
        this._getCreateProject() // 基本信息布局
      }
    },
    _editProject() {
      this.spinning = true
      editProject({ oid: this.changeOid, userId: this.userId }).then(({data}) => {
        this.baseInfoHandle(data)
      })
    },
    baseInfoHandle(data) {
      this.spinning = false
      if (data.success && data.data && data.data[0]) {
        let formFidlds = {}
        data.data[0].rows.forEach(item => {
          item.items.forEach(itm => {
            if(itm.id === 'planActivityReference') {
              itm.formType = 'text'
              // const { setFieldsValue } = this.form;
              // setFieldsValue({
              //   planActivityReference:itm.value
              // })
              // this.planActivityReferenceId = itm.valueInner;
              this.planActivityReference = itm.valueInner;
            } else if (itm.id === 'responsibleUserReference') {
              // itm.formType = 'button'
              itm.formType = 'text'
              this.responsibleUserReferenceCopy  = itm.valueInner;
            } else if (itm.id === 'ReasonForChange' || itm.id==='ChangeImpact' || itm.id==='BeforeChange' || itm.id==='AfterChange') {
              itm.formType = 'textarea'
            }
            // if(itm.id !== 'planActivityReference') {
            //   let selectData = []
            //   for(let key in itm.selects) {
            //     selectData.push({
            //       name: itm.selects[key],
            //       id: key
            //     })
            //   }
            //   itm.selects = selectData
            // }
            // itm.selects = selectData
            formFidlds[itm.id] = itm.value
          })
        })
        this.baseInfoArr = data.data[0].rows
        this.formFidlds = formFidlds
      }
    },
    // 基本信息布局
    _getCreateProject() {
      getCreateProject({userId: this.userId, "objType": "com.pisx.pmgt.change.PIProjectChangeRequest", oid: this.changeOid}).then(({data}) => {
        this.baseInfoHandle(data)
      })
    },
    _getPageSelectPrincipal(val) {
      this.processUsers = chooseUserList;
      return false;
      this.processUsers = [];
      getPageSelectPrincipal({
        oid: this.changeOid || `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem('oid')}`,
        userId: this.userId,
        processName: 'PIProjectChangeRequestWf',
        type: 'com.pisx.pmgt.change.PIProjectChangeRequest',
        attributes:JSON.stringify({category:val || ''})
      }).then((results) => {
        if (results && results.data.success) {
          let optionUser = []
          optionUser = results.data.data[0].selectedUsers
          results.data.data.forEach((item, index) => {
            if (index === 0) return
            this.processUsers.push({
              name: item.name,
              oid: item.oid,
              required: item.required,
              selsectData: optionUser,
              checkSelsectData: []
            })
          })
        } else {
          this.$message.error(results.data.message)
        }
      })
    },
    changeSelect(e,val){
      if(val=='变更类别'){
        this._getPageSelectPrincipal(e)
      }
    },
    /**
     *获取流程人
     */
    getProcess() {
      getWFSelectPrincipal({
        oid: this.sourceData.workItemOid,
      }).then((results) => {
        if (results && results.data.success) {
          //每个下拉菜单的值
          let optionUser = []
          optionUser = results.data.data[0].selectedUsers
          results.data.data.forEach((item, index) => {
            if (index === 0) return
            //下拉框默认显示的值
            let initUser = []
            initUser = item.initUsers.map((rec) => {
              return rec.fullname
            })
            this.processUsers.push({
              name: item.name,
              oid: item.oid,
              required: item.required,
              selsectData: optionUser,
              checkSelsectData: initUser
            })
          })
        } else {
          this.$message.error(results.data.message)
        }
      })
    },
    // 表格数据
    _getTaskBookByProject() {
      getTaskBookByProject({ oid: `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem('oid')}`, userId: this.userId }).then(({data}) => {
        if (data.success) {
          if (data.data && data.data.length) {
            this.bookOid = data.data[0].bookOid
            this.bookVersion = data.data[0].version;
          } else {
            this.$message.info(data.message || '暂无任务书数据')
          }
        }
      })
    },
    //获取近期人员
    getManager() {
      getManagerMiddle().then(results=>{
        if(results.data.staffList){
          const arr = results.data.staffList.split(',')
          const newStaffList = arr.filter((item,index) => {
            return arr.indexOf(item,0) ===index
          }) 
          let newArr = []
          let newList = []
          if(newStaffList.length > 10){
            newList = newStaffList.slice(-10)
          }else{
            newList = newStaffList
          }
          let params = {
            match: true,
            userIds: newList,
          }
          searchUserIdMiddle(params).then(results1=>{
            results1.data.map(item=>{
              item.checked = false
            })
            newArr.push(results1.data) 
            const dataAll = newArr.flat()
            this.$set(this,"projectMemberSelectData",dataAll)
            this.$store.commit('setItemArr',this.projectMemberSelectData)
            this.addMemberAddDialog = true
          })
        }
      })
      },
    // 附件只有一行数据回调
    onlyOneHandle(val) {
      this.attachmentSelect = val
    },
    // 附件复选框
    selectedData(select) {
      this.attachmentSelect = select
    },
    upload(fileArrList) {
      this.fileArrList = fileArrList
    },
    handleRemove(v1,v2){
      this.fileArrList = v2;
    },
    backData() {
      history.go(-1);
    },
    /**
     * commonProcessSettings 组件回调方法
     * 功能： 提交审核人
     */
    submitProcessPeople(radioVal1, desVal1, userId) {
        this.radioVal1 = radioVal1
        this.desVal1 = desVal1
        this.reassignUser = userId
        this.$refs.commonProcessSettings.handleChange()
    },
    fields(val1) {
      let data1 = {oid: this.sourceData.workItemOid, processUsers: JSON.stringify(val1)}
      this.submitData(data1)
    },
    /**
     * 功能：提交流程操作--转办
     */
    onCompleteWorkItemDivTransfer(radioVal1, desVal1, reassignUser) {
      radioVal1 = this.radioVal1
      desVal1 = this.desVal1
      reassignUser = this.reassignUser
      let parms = {}
      if (this.radioArr.length > 0) {
        parms = {
          oid: this.sourceData.workItemOid,
          routeChoice: radioVal1,
          comment: desVal1,
          custActVar: '',
          reassignUser: reassignUser
        }
      } else {
        parms = {
          oid: this.sourceData.workItemOid,
          routeChoice: '',
          comment: desVal1,
          custActVar: '',
          reassignUser: reassignUser
        }
      }
      if (this.radioArr.length > 0 && radioVal1 == '') {
        this.$message.error('请选择操作！');
        return
      }
      if (this.radioVal1 === 'TRANSFER' && this.reassignUser == '') {
        this.$message.error('请选择转办人员！');
        return
      }
      if (desVal1 == '') {
        this.$message.error('请输入处理意见！');
        return
      }
      this.spinning = true;
      reassignWorkItem(parms).then((results1) => {
        if (results1 && results1.status === 200) {
          if (results1.data && results1.data.success) {
            let tabArrNew1 = JSON.parse(sessionStorage.getItem('tabArr'))
            this.$message.success('流程操作成功！')
            tabArrNew1 = tabArrNew1.filter((recs1) => {
              return recs1.title !== '编辑变更'
            })
            this.$store.commit('SET_TABS', tabArrNew1)
            this.$router.push('/toDoPage');
          } else {
            this.$message.error(results1.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
        this.spinning = false;
      }).catch(()=>{
        this.spinning = false;
      })
    },
    /**
     * 功能：提交流程操作
     */
    onCompleteWorkItemDiv(radioVal1, desVal1) {
      radioVal1 = this.radioVal1
      desVal1 = this.desVal1
      let parms = {}
      if (this.radioArr.length > 0) {
        parms = {
          oid: this.sourceData.workItemOid,
          routeChoice: radioVal1,
          comment: desVal1,
          custActVar: '',
          reassignUser: ''
        }
      } else {
        parms = {
          oid: this.sourceData.workItemOid,
          routeChoice: '',
          comment: desVal1,
          custActVar: '',
          reassignUser: ''
        }
      }
      if (this.radioArr.length > 0 && radioVal1 == '') {
        this.$message.error('请选择操作！');
        return
      }
      if (desVal1 == '') {
        this.$message.error('请输入处理意见！');
        return
      }
      this.spinning = true;
      completeWorkItem(parms).then((results) => {
        if (results && results.status === 200) {
          if (results.data && results.data.success) {
            this.$message.success('流程操作成功！')
            let tabArrNew = JSON.parse(sessionStorage.getItem('tabArr'))
            tabArrNew = tabArrNew.filter((rec) => {
              return rec.title !== '编辑变更'
            })
            this.$store.commit('SET_TABS', tabArrNew)
            this.$router.push('/toDoPage');
          } else {
            this.$message.error(results.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
        this.spinning = false;
      }).catch(()=>{
        this.spinning = false;
      })
    },
    fillZero(str) {
      let realNum;
      if (str < 10) {
          realNum = '0' + str;
      } else {
          realNum = str;
      }
      return realNum;
    },
    getTime(){
      let myDate = new Date();
      let myYear = myDate.getFullYear(); 
      let myMonth = myDate.getMonth() + 1;
      let myToday = myDate.getDate(); 
      let myDay = myDate.getDay(); 
      let myHour = myDate.getHours(); 
      let myMinute = myDate.getMinutes(); 
      let mySecond = myDate.getSeconds(); 
      let nowTime;
      nowTime = myYear + '/' + this.fillZero(myMonth) + '/' + this.fillZero(myToday) + '/' + ' ' + this.fillZero(myHour) + ':' + this.fillZero(myMinute) + ':' + this.fillZero(mySecond)
      return nowTime;
    },
    submitData(rows) {
      // 基本信息校验
      this.form.validateFieldsAndScroll((err, values) => {
        Object.keys(values).forEach((key) => {
          if(!values[key]){
            values[key] = ''
          }
        })
        if (!err) {
          values.responsibleUserReference = this.responsibleUserReferenceCopy ? this.responsibleUserReferenceCopy : '';
          // values.planActivityReference = this.planActivityReferenceId ? this.planActivityReferenceId : '';
          values.number = "PCR"+values.name;
          values.stateDisPlay = '正在审阅';
          values.state = 'UNDERREVIEW';
          values.createDate = this.getTime();
          values.planActivity = values.planActivityReference;
          // 流程处理人校验
          if(this.changeOid){ //编辑
            if(values.DelayDate){
              values.DelayDate = values.DelayDate.replace(/\//g,'-')
            }
            let params = new FormData()
            let oldFileArr = []
            let newFileArr = []
            this.fileArrList.forEach(item => {
              if(item.lastModifiedDate) {
                newFileArr.push(item)
              } else {
                oldFileArr.push(item)
              }
            })
            if(oldFileArr.length){
              let oldAttachments = oldFileArr.map(item=>{
                return item.uid
              }).toString();
              params.append('attachments', oldAttachments)
            }
            params.append('oid', this.changeOid)
            params.append('userId', this.userId)
            params.append('attributes', JSON.stringify(values))
            newFileArr.forEach((file) => {
              params.append(file.name, file);
            });
            this.spinning = true;
            saveChangeRequest(params).then(({data}) => {
              if (data.success) {
                if(this.sourceData.operation=='修改'){
                  this.spinning = true;
                  updateTeamPrincipal(rows).then((res1) => {
                    if (res1 && res1.status == 200) {
                      if (res1.data.success) {
                        this.$message.success('提交成功');
                        //提交审核操作
                        if (this.radioVal1 === 'TRANSFER') {
                          this.onCompleteWorkItemDivTransfer(this.radioVal1, this.desVal1, this.reassignUser)
                        } else {
                          this.onCompleteWorkItemDiv(this.radioVal1, this.desVal1)
                        }
                      } else {
                        this.$message.error(results.data.message)
                      }
                    } else {
                      this.$message.error('接口失败！')
                    }
                    this.spinning = false;
                  }).catch(()=>{
                    this.spinning = false;
                  })
                }else{
                  this.$message.success('编辑成功')
                  let tabArrNew2 = JSON.parse(sessionStorage.getItem('tabArr'))
                  tabArrNew2 = tabArrNew2.filter((recs1) => {
                    return recs1.title !== '编辑变更'
                  })
                  this.$store.commit('SET_TABS', tabArrNew2)
                  history.go(-1);
                }
              } else {
                this.$message.error('编辑失败')
              }
              this.spinning = false;
            }).catch(()=>{
              this.spinning = false;
            })
          }else{ //新建
            this.$refs.processUser.form.validateFieldsAndScroll((err1, values1) => {
              if (err1==null) {
                let arr = [];
                arr = sessionStorage.getItem('changeItem') ? JSON.parse(sessionStorage.getItem('changeItem')) : [];
                if(arr.length){
                  arr.unshift(values);
                  sessionStorage.setItem('changeItem',JSON.stringify(arr))
                }else{
                  sessionStorage.setItem('changeItem',JSON.stringify([values]))
                }
                this.$message.success('创建成功')
                let tabArrNew = JSON.parse(sessionStorage.getItem('tabArr'))
                tabArrNew = tabArrNew.filter((rec) => {
                  return rec.title !== '创建变更'
                })
                this.$store.commit('SET_TABS', tabArrNew)
                this.$router.push('/single/projectAlteration')
                return false;
                let processUsers = values1['OR:wt']['workflow']['definer']
                let processUsersData = []
                for(let key in processUsers) {
                  if(processUsers[key]){
                    let users = []
                    if(typeof processUsers[key] === 'string') {
                      users = [{id: processUsers[key]}]
                    } else {
                      processUsers[key].map(item => {
                        users.push({id: item})
                      })
                    }
                    processUsersData.push({
                      "oid": "wt.workflow.definer." + key,
                      "users": users
                    })
                  }
                }
                let params = new FormData()
                params.append('oid', `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem('oid')}`)
                params.append('userId', this.userId)
                params.append('attributes', JSON.stringify(values))
                params.append('processUsers', JSON.stringify(processUsersData))
                this.fileArrList.forEach(file => {
                  params.append(file.name, file)
                })
                this.spinning = true;
                saveChangeRequest(params).then(({data}) => {
                  if (data.success) {
                    this.$message.success('创建成功')
                    let tabArrNew = JSON.parse(sessionStorage.getItem('tabArr'))
                    tabArrNew = tabArrNew.filter((rec) => {
                      return rec.title !== '创建变更'
                    })
                    this.$store.commit('SET_TABS', tabArrNew)
                    this.$router.push('/single/projectAlteration')
                  } else {
                    this.$message.error('创建失败')
                  }
                  this.spinning = false;
                })
              }
            });
          }
        }else{
          this.$message.error('带*的为必填项')
        }
      });
    },
    callback(key) {
      this.defaultTagId = key
      document.querySelector("#" + key).scrollIntoView(
        // {
        //   behavior: "smooth"
        // }
      );
    },
  }
}
</script>
<style lang="less" scoped>
.properContent{
  padding-right: 10px;
  position: relative;
    .contentLength{
      position: absolute;
      right: 26px;
      bottom: 2px;
      font-size: 12px;
      color:#bebebe
    }
}
  /deep/ .commonTable{
    .ant-table-body{
      min-height: auto;
    }
    .ant-table-placeholder{
      min-height: auto;
      border: none;
    }
  }
  /deep/ .has-error .ant-form-explain, .has-error .ant-form-split{
    display: none;
    height: 0;
    border:1px solid #d9d9d9;
    background: #e8f0fd;
  }
  /deep/ .has-success .ant-form-explain, .has-success .ant-form-split{
    display: none;
  }
  /deep/ .has-error .ant-input,.has-error .ant-input:hover{
    border:1px solid #d9d9d9;
    background: #e8f0fd;
  }
  /deep/ .has-error .ant-select-selection{
    border:1px solid #d9d9d9;
    background: #e8f0fd;
  }
  /deep/ .has-error .ant-input-affix-wrapper .ant-input, .has-error .ant-input-affix-wrapper .ant-input:hover{
    border:1px solid #d9d9d9;
    background: #e8f0fd;
  }
  /deep/ .has-error .ant-input:hover{
    border:1px solid #d9d9d9;
    background: #e8f0fd;
  }
  /deep/ .has-error .ant-select-selection:focus{
    border:1px solid #5f8de3 !important;
    box-shadow: 0 0 0 2px rgba(115,136,192,0.2) !important;
  }
  /deep/ .has-error .ant-select-selection:hover{
    border-color: #5f8de3 !important;
  }
  /deep/ .ant-select-arrow{
    color:#d9d9d9 !important;
  }
  /deep/ .has-error .ant-input-affix-wrapper .ant-input:focus{
    border-color: #5f8de3 !important;
    border-right-width: 1px !important;
    box-shadow: 0 0 0 2px rgba(115,136,192,0.2) !important;
  }
  /deep/ .ant-select-focused{
    border-color: #5f8de3 !important;
    border-right-width: 1px !important;
    box-shadow: 0 0 0 2px rgba(115,136,192,0.2) !important;
 }
  /deep/ .has-error .ant-input-affix-wrapper .ant-input:hover{
    border-color: #5f8de3 !important;
    background: #e8f0fd;
  }
  /deep/ .has-error .ant-select-open .ant-select-selection, .has-error .ant-select-focused .ant-select-selection{
    border-color: #5f8de3 !important;
    border-right-width: 1px !important;
    box-shadow: 0 0 0 2px rgba(115,136,192,0.2) !important;
  }
</style>
<style lang="less" scoped>
  .alteration-wrapper{
    background-color: #fff;
    padding: 0 21px;
    .ant-tabs{
      position: sticky;
      top: 0;
      z-index: 100;
      background: #fff;
    }
    .files{
      margin-top:20px;
      display:flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    .contentBox{
      padding-top: 11px;
      .content{
        // position: relative;
        // top: 0px;
        // bottom: 72px;
        // padding-bottom: 72px;
        overflow-y: scroll;
        height: calc(100vh - 120px);
        width: calc(100% + 8px);
        padding-bottom: 75px;
        .title{
          color: #333;
          font-size: 18px;
          font-weight: bold;
        }
        .form-box{
          padding-top: 20px;
          .row-item {
            display: flex;
            align-items: center;
            padding-bottom: 16px;
            /deep/ .ant-form-item {
              display: flex;
              margin-bottom: 0;
              &:nth-of-type(2n - 1) {
                padding-right: 39px;
              }
              .required{
                color: red;
                margin-right: 3px;
              }
            }
            .ant-btn{
              color: #ccc;
              width: 100%;
              text-align: left;
              padding: 0 11px;
            }
          }
        }
        /deep/ .ant-form-item-label, .cell-item .label{
          min-width: 160px;
          color: #666;
          font-size: 14px;
          text-align: left;
        }
        /deep/.ant-form-item-children{
          width: 100%;
          display: block;
        }
        /deep/ .ant-form-item-control-wrapper{
          flex: 1;
        }
        .titleBox{
          padding: 24px 0 21px 0;
        }
        .processSet{
          padding-top: 42px;
          .process-explain{
            padding: 16px 0;
            font-size: 12px;
            // color: #386BD7;
          }
        }
        .process-user-select{
          .process-user {
            width: 780px;
            display: flex;
            padding-bottom: 16px;
            .ant-select{
              flex: 1;
            }
            span{
              min-width: 115px;
              margin-right: 10px;
            }
          }
        }
      }
    }
    .footer {
      display: flex;
      justify-content: flex-end;
      border-top: 1px solid #ddd;
      padding: 12px 32px 12px 12px;
      background-color: #fff;
      box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.2);
      position: fixed;
      width: 100%;
      bottom: 0;
      z-index: 9;
      left: 0;
      /deep/ .ant-btn {
        width: 72px;
        margin-left: 10px;
      }
    }
  }
</style>